#! /usr/bin/env node

// anywhere

const {existsSync,statSync,readdirSync,readFileSync} = require('fs');
const path = require('path');
const http = require('http');
const args = process.argv.slice(2);
let POST = 8080

function createserve(){
    http.createServer((req,res)=>{
        // console.log(req.url)
        let rootpath = path.join(process.cwd(),req.url);
        if(existsSync(rootpath)){
            // 路径是否存在
            if(statSync(rootpath).isDirectory()){
                // 是否是个文件夹
                let htmls = readFileSync(path.join(__dirname,'../public/index.html'),'utf-8');
                let arrs = readdirSync(rootpath)

                let listml = arrs.map(item=>{
                    return `<li>
                    <a href=${path.join(req.url,item)}>${item}</a>
                </li>`
                }).join("")
                htmls = htmls.replace('{{123}}',listml)
                res.end(htmls)
            }else{
                res.end(readFileSync(rootpath),'utf-8')
            }
        }
    }).listen(POST,()=>{
        console.log('登陆成功！！！')
    })
}

if(args.length == 0){
    console.log('ok了')
    createserve()
}else if(args[0] == '-v'){
    console.log('版本号是1.0.0')
}else if(args[0] == '-p'){
    console.log('端口号是'+args[1])
    POST = args[1];
    createserve()
}   

